﻿using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.Environment.Extensions;
using Orchard.Indexing;
using System.Data;

namespace Rework.CommerceHistory.Migrations {
    [OrchardFeature("Rework.CommerceRoleAssignment")]
    public class CommerceRoleAssignmentMigrations : DataMigrationImpl {
        public int Create() {
            SchemaBuilder.CreateTable("CommerceRoleAssignmentPartRecord", table => table
                .ContentPartRecord()
                .Column("DateActivated", DbType.DateTime, c => c.Nullable())
                .Column("DateExpires", DbType.DateTime, c => c.Nullable())
                );

            SchemaBuilder.CreateTable("CommerceProductRolesRecord", table => table
                .Column("Id", DbType.Int32, c => c.PrimaryKey().Identity())
                .Column("ProductId", DbType.Int32)
                .Column<int>("Role_id")
                );

            // Add in Foreign Key if neccessary (at this point, pretty small file set so may not be worth it)
            //  See BundleProductsBundle in Nwazet.Commerce for an example
            
            ContentDefinitionManager.AlterPartDefinition(
                "CommerceRoleAssignmentPart", builder => builder
                .Attachable());

            ContentDefinitionManager.AlterTypeDefinition("Product", cfg => cfg
                .WithPart("CommerceRoleAssignmentPart")
                );
            
            return 1;
        }

        public int UpdateFrom1() {
            // Remove wrong columns
            SchemaBuilder.AlterTable("CommerceRoleAssignmentPartRecord", table => table
                .DropColumn("DateActivated"));
            SchemaBuilder.AlterTable("CommerceRoleAssignmentPartRecord", table => table
                .DropColumn("DateExpires"));

            // Add correct columns
            SchemaBuilder.AlterTable("CommerceRoleAssignmentPartRecord", table => table
                .AddColumn("NumberOfPeriods", DbType.Int32));
            SchemaBuilder.AlterTable("CommerceRoleAssignmentPartRecord", table => table
                .AddColumn("PeriodType", DbType.String));
            return 2;
        }
    }
}
